#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, urllib, json
import gobject
from Message import Message
class QueryBox(object):
    def __init__(self):
        self.opener = urllib2
        self.gmail = ''
        self.time = ''
        self.connectionCheck = True
                
    def setEmail(self, gmail):
        #print gmail
        self.gmail = gmail
        self.time = ''
        self.nextTime = ''
        print self.gmail
        
    def add(self, url):
        if self.gmail:
            req = self.opener.Request('http://140.112.244.202/rdm/API/add', 
                urllib.urlencode({'user':'"'+self.gmail+'"', 'url':'"'+url+'"'}),
                {'Content-Type':'application/x-www-form-urlencoded'})
            id = None
            try:
                resp = self.opener.urlopen(req)
                id = int(resp.read())
                resp.close()
                del resp
            except ValueError:
                gobject.idle_add(Message.urlValueError)
            except urllib2.HTTPError as e:
                gobject.idle_add(Message.urlAuthError, e.code)
            except urllib2.URLError:
                gobject.idle_add(Message.urlConnectionError)
            del req
            print id, 'xdd'
            return id
        return None
            
    def __getByTime(self, _time):
        req = urllib2.Request('http://140.112.244.202/rdm/API/getByTime', 
            urllib.urlencode({'user':'"'+self.gmail+'"', 'time':'"'+_time+'"'}),
            {'Content-Type':'application/x-www-form-urlencoded'})
        tmpUrlMap = {}
        try:
            resp = urllib2.urlopen(req)
            jsonResp = json.loads(resp.read())
            for i in jsonResp:
                id = i['id']
                tmpUrlMap[id] = i
            del jsonResp
            resp.close()
            self.connectionCheck = True
        except ValueError:
            gobject.idle_add(Message.urlValueError)
        except urllib2.HTTPError as e:
            gobject.idle_add(Message.urlAuthError, e.code)
        except urllib2.URLError:
            if self.connectionCheck:
                gobject.idle_add(Message.urlConnectionError)
                self.connectionCheck = False
        del req
        return tmpUrlMap
            
    def __get(self, type):
        req = urllib2.Request('http://140.112.244.202/rdm/API/get', 
            urllib.urlencode({'user':'"'+self.gmail+'"', 'type':'"'+type+'"'}),
            {'Content-Type':'application/x-www-form-urlencoded'})
        tmpUrlMap = {}
        try:
            resp = urllib2.urlopen(req)
            jsonResp = json.loads(resp.read())
            for i in jsonResp:
                id = i['id']
                tmpUrlMap[id] = i
            del jsonResp
            resp.close()
            self.connectionCheck = True
        except ValueError:
            gobject.idle_add(Message.urlValueError)
        except urllib2.HTTPError as e:
            gobject.idle_add(Message.urlAuthError, e.code)
        except urllib2.URLError:
            if self.connectionCheck:
                gobject.idle_add(Message.urlConnectionError)
                self.connectionCheck = False
        del req
        return tmpUrlMap
        
    def getById(self, id):
        req = self.opener.Request('http://140.112.244.202/rdm/API/getById',
            urllib.urlencode({'user':'"'+self.gmail+'"', 'id':id}),
            {'Content-Type':'application/x-www-form-urlencoded'})
        try:
            resp = self.opener.urlopen(req)
            jsonResp = json.loads(resp.read())
            id = jsonResp['id']
            if id >= 0:
                url = jsonResp['url']
                status = jsonResp['status']
                create = jsonResp['create']
                update = jsonResp['update']
                progress = jsonResp['progress']
                del req
                del jsonResp
                resp.close()
                return [id, url, status, create, update, progress]
            del req
            del jsonResp
            resp.close()
        except ValueError:
            gobject.idle_add(Message.urlValueError)
        except urllib2.HTTPError as e:
            gobject.idle_add(Message.urlAuthError, e.code)
        except urllib2.URLError:
            gobject.idle_add(Message.urlConnectionError)
        del req
        return []
        
        
    def __upd(self, update):
        newUpdate = json.dumps(update)
        req = self.opener.Request('http://140.112.244.202/rdm/API/upd',
            urllib.urlencode({'user':'"'+self.gmail+'"', 'update':newUpdate}),
            {'Content-Type':'application/x-www-form-urlencoded'})
        try:
            resp = self.opener.urlopen(req)
            jsonResp = json.loads(resp.read())
            resp.close()
            del newUpdate
            del req
            return jsonResp
        except ValueError:
            gobject.idle_add(Message.urlValueError)
        except urllib2.HTTPError as e:
            gobject.idle_add(Message.urlAuthError, e.code)
        except urllib2.URLError:
            gobject.idle_add(Message.urlConnectionError)
        return []
        
    def getUpdate(self):
        if self.gmail:
            tmpMap = {}
            #if self.time:
            #    print self.time
            #    tmpMap = self.__getByTime(self.time)
            #else:
            tmpMap = self.__get('all')
            if not tmpMap:
                return {}
            return tmpMap
            #
            #returnMap = {}
            #it = tmpMap.values()
            
            # get the oldest time if time is not set
            #if not self.time:
            #    self.time = it[0]['update']
            #    for t in it:
            #        if self.time > t['update']:
            #            self.time = t['update']
            #            self.nextTime = self.time
            #else:
            #    self.time = self.nextTime
            
            #for t in it:
            #    if t['update'] >= self.time:
            #        returnMap[t['id']] = t
            #        if self.nextTime < t['update']:
            #            self.nextTime = t['update']
            #del tmpMap
            #return returnMap
        print 'No gmail'
        return {}
        
    def notify(self, update):
        if self.gmail and update:
            l = self.__upd(update)
            print l

        
# TODO: write to file
